package main

import (
	"context"
	"errors"

	"go-micro.dev/v4/metadata"
	"go-micro.dev/v4/server"
)

func AuthMiddleware() server.HandlerWrapper {
	return func(h server.HandlerFunc) server.HandlerFunc {
		return func(ctx context.Context, req server.Request, rsp interface{}) error {
			// Extract the metadata from the context
			meta, ok := metadata.FromContext(ctx)
			if !ok {
				return errors.New("no auth meta-data found in request")
			}

			// Check if the token is present and valid
			token, ok := meta["Token"]
			if !ok || token != "valid-token" {
				return errors.New("invalid or missing auth token")
			}

			// Call the next handler
			return h(ctx, req, rsp)
		}
	}
}


package main

import (
        "context"
        "fmt"

        "go-micro.dev/v4"
)

type Greeter struct{}

type HelloRequest struct {
}

type HelloResponse struct {
}

func (g *Greeter) Hello(ctx context.Context, req *HelloRequest, rsp *HelloResponse) error {
        fmt.Println("Hello service was called")
        // Business logic goes here...
        return nil
}

func main() {
        service := micro.NewService(
                micro.Name("hello"),
                micro.WrapHandler(AuthMiddleware()),
        )

        service.Init()

        if err := micro.RegisterHandler(service.Server(), new(Greeter)); err != nil {
                fmt.Println(err)
                return
        }

        if err := service.Run(); err != nil {
                fmt.Println(err)
        }
}